<?php
/**
*  Project Name: 芝士活动
*	公用函数
*  @package:   functions
*  @author:    邝达峰 <tcyh026@163.com>
*  @date 2017年07月18日
*/

/**
* 自动加载函数
* @param string $class
* @return bool
*/
function __autoload($class)
{
	#加载主类
	if (Action::loadMain($class) === true){
		return true;
	}
	#加载模块类
	if (Action::loadModule($class) === true){
		return true;
	}
	#加载工具类
	if (Action::loadTool($class) === true){
		return true;
	}
	#加载数据库操作类
	if (Action::loadModels($class) === true){
		return true;
	}
}

/**
* 加载插件文件
* @param $plugins_path 插件路径
* @return null
*/
function load_plugins($plugins_path)
{
	#打开目录句柄
	if($handle = opendir($plugins_path)){
		#从目录句柄中读取条目
		while (false !== ($file = readdir($handle))) {
			#判断是否php后缀
			if(preg_match("/\.php$/",$file))
			{
				#批量包含文件
				if(!@include_once($plugins_path.DIRECTORY_SEPARATOR.$file))
				{
					#错误抛出
					throwException($GLOBALS['lang']['INCLUDE_IS_NOT_EXISTS']);
				}
			}
		}
		#关闭目录句柄
		closedir($handle);
	}
}


/**
 * 异常处理
 * @param $msg 异常抛出展示信息
 * @param $type 异常抛出类型
 * @$code $code 异常代码
 */
function throwException($msg,$type='BaseException',$code=0)
{
	#是否调试模式
	if(SYSTEM_DEBUG){
		halt($msg);
	}
	elseif(class_exists($type,false)){
		if($GLOBALS['cfg']['IS_LOG'])
		{
			$oErr = new $type($msg,$code);
			@$oErr->__toString();
		}
		#跳转404页面
		goTo404();
	}
	else
	{
		#设置网站头部编码
		header("Content-Type:text/html;charset=".WEB_HEADER_CHARSET);
		exit($msg);
	}
}

/**
 * 错误输出 
 * 在调试模式下面会输出详细的错误信息
 * 否则就定向到指定的错误页面
 * @param $error 错误输出信息
 */

function halt($error) {
	$e = array();
	#调试模式下输出错误信息
	if(!is_array($error)) {
		$trace = debug_backtrace();
		//array_shift($trace);
		$e['message'] = $error;
		$e['file'] = $trace[0]['file'];
		$e['class'] = $trace[0]['class'];
		$e['function'] = $trace[0]['function'];
		$e['line'] = $trace[0]['line'];
		$traceInfo='';
		$time = date("y-m-d H:i:s");

		foreach($trace as $t)
		{
			$traceInfo .= '['.$time.'] '.$t['file'].' ('.$t['line'].') ';
			$traceInfo .= $t['class'].$t['type'].$t['function'].'(';
			foreach ($t['args'] as $v)
			{
				if (is_object($v))
				$v = print_r($v,true);

				$traceInfo .= $v.",";
			}
			$traceInfo .=")<br/>";
		}
		$e['trace']  = $traceInfo;
	}else {
		$e = $error;
	}
	include  USER_THEME_PATH.'system'.DIRECTORY_SEPARATOR.'exception.tpl.php';
	exit();
}

/**
 * 跳转404页面
 */
function goTo404()
{
	#判断是否输出404日志
	if(IS_EXPORT_404_LOG)
	{
		$oErr = new BaseException('404 Not Found',0,false,SYSTEM_LOG_PATH.DIRECTORY_SEPARATOR.'404'.DIRECTORY_SEPARATOR.date('y_m_d').'.log');
		@$oErr->__toString();
	}
	@header("HTTP/1.1 404 Not Found");
	#HTTP/1.1
	@header('Cache-Control: no-store, no-cache, must-revalidate');
	#HTTP/1.1
	@header('Cache-Control: pre-check=0, post-check=0, max-age=0');
	#HTTP/1.0
	@header('Pragma: no-cache');
	#设置网站头部编码
	@header("Content-Type:text/html;charset=".WEB_HEADER_CHARSET);
	session_start();
	//header("Location:".WWW_SITE_ROOT."/n404.html");//跳转方式
	#读取404模板
	Action::getSmarty()->display(SYSTEM_THEME_PATH.'front/n404.html');
	exit();
}


/**
 * 跳转301
 */
function goTo301($url){
	header("HTTP/1.1 301 Moved Permanently");
	header("Location: $url");
	exit;
}

/**
* 页面重定向
* @param string $url 重定向链接
* @param $target_window 重写类型 self,自身，top，上一级
*/

function redirect($url, $target_window='self')
{
	if ($target_window == 'self')
	{
		$is_sent = headers_sent();
		if($is_sent == false){
			header("Location: $url");
		}
		else{
			print "<meta http-equiv=\"refresh\" content=\"0; url=$url\">\n";
		}
	}
	elseif ($target_window == 'top'){
		echo "<script language='javascript' type='text/javascript'>";
		echo 'if (!document.all) window.top.location.href = "'.$url.'"; else{document.write("<a href=\''.$url.'\' style=\'display:none\'>&nbsp;</a>");
document.getElementsByTagName(\'A\')[0].click();}';

		echo "</script>";
	}
	exit();
}



/**
*  页面跳转返回
*  @param:  $message 跳转信息
*  @param:  $go  跳转返回上一级
*  @param:  $isReload  是否本页面更新
*  @return: NULL
*/
function alertBack($message = '',$go = -1,$isReload = false)
{
	echo '<script type="text/javascript">';
	if(!empty($message)){
		echo "alert('$message');";
	}
	if(!empty($_SERVER['HTTP_REFERER'])){
		echo 'if (!document.all) location.href = "'.$_SERVER['HTTP_REFERER'].'"; else{document.write("<a href=\''.$_SERVER['HTTP_REFERER'].'\' style=\'display:none\'>&nbsp;</a>");document.getElementsByTagName(\'A\')[0].click();}';
	}
	else{
		if($go != 0){
			echo 'window.history.go('.$go.');';
			if($isReload) {
				echo 'window.location.reload();';
			}
		}
	}
	echo '</script>';
	exit;
}

/**
* 只显示提示信息,不做任何跳转
* @param string $message 跳转信息
* @return: NULL
*/
function alert($message = '')
{
	if(empty($message)){
		return ;
	}
	echo '<script type="text/javascript">';
	echo "alert('$message');";
	echo '</script>';
}

/**
*  提示信息跳转页面
*  @param:  $message 提示信息
*  @param:  $url     跳转地址
*  @return: NULL
*/
function alertGoto($message,$url='/',$target='')
{
	echo "<script>";
	if(!empty($message)){
		echo "alert('$message');";
	}
	if(!empty($target)){
		$target = $target.'.';
		echo 'window:'.$target."location='".$url."';";
	}else{
		echo 'if (!document.all) window.location.href = "'.$url.'"; else{document.write("<a href=\''.$url.'\' style=\'display:none\'>&nbsp;</a>");document.getElementsByTagName(\'A\')[0].click();}';
	}
	echo "</script>";
	exit();
}


/**
 * 设置内存限制值
 * @return bool
 */
function setMemoryLimit()
{
	$valueInit = getMemoryValue();
	if( ($valueInit === false || $valueInit < MEMORY_LIMIT ) && @ini_set('memory_limit', MEMORY_LIMIT.'M')){
		return true;
	}
	return false;
}

/**
 * 得到当前内存限制值
 * @return bool
 */
function getMemoryValue()
{
	if($memory = ini_get('memory_limit')){
		return substr($memory, 0, strlen($memory) - 1);
	}
	return false;
}

/**
 * 得到客户端IP地址
 * @author 邝达峰
 */
function getClientIp()
{
	if($_SERVER["HTTP_X_FORWARDED_FOR"]){
		$ip = $_SERVER["HTTP_X_FORWARDED_FOR"];
	}
	elseif ($_SERVER["HTTP_CLIENT_IP"]){
		$ip = $_SERVER["HTTP_CLIENT_IP"];
	}
	elseif ($_SERVER["REMOTE_ADDR"]){
		$ip = $_SERVER["REMOTE_ADDR"];
	}
	elseif (getenv("HTTP_X_FORWARDED_FOR")){
		$ip = getenv("HTTP_X_FORWARDED_FOR");
	}
	elseif (getenv("HTTP_CLIENT_IP")){
		$ip = getenv("HTTP_CLIENT_IP");
	}
	elseif (getenv("REMOTE_ADDR")){
		$ip = getenv("REMOTE_ADDR");
	}
	else{
		$ip = "Unknown";
	}
	return $ip;
}
/**
 * 自定义var_dump函数
 * @author 何向成
 */
function var_dump2($a){
	echo '<pre>';
	var_dump($a);
}

//获取图片宽、高、大小、类型
function images_size($path){

	$arrayimg=array();
	$images_path=basename($path);
	$images_path=str_replace("s_","", $images_path);
	$images_path=str_replace("m_","", $images_path);
	if(substr_count($images_path,"_")>2){
		$images_path = preg_replace("/x.+?\./","",$images_path);
		$images=explode("_",$images_path);
		$arrayimg[0]=$images[1];
		$arrayimg[1]=$images[2];
		$n=strpos($images[3],".");
		$arrayimg[2]=substr($images[3],$n+1,strlen($images[3])-1);
		$arrayimg[3]=substr($images[3],0,$n);
	}else{
		$arrayimg=@getimagesize($path);
	}
	return $arrayimg;
}


/**
 * 基于表单ajax json_encode 编码
 * @author lee
 * @params mix
 * @return mix
 */ 
function url_encode($str) {
	if(is_array($str)) {
		foreach($str as $key=>$value) {
			$str[urlencode($key)] = url_encode($value);
		}
	} else {
		$str = urlencode($str);
	}

	return $str;
}

/**
 * 判断是否移动端登录
 * @author lee
 */
function mobile_login() {
	if(empty($_SERVER['HTTP_USER_AGENT']) ) {
		$status = false;
	}elseif(
	strpos($_SERVER['HTTP_USER_AGENT'], 'Mobile') !== false  // many mobile devices (all iPhone, iPad, etc.)
	|| strpos($_SERVER['HTTP_USER_AGENT'], 'Android') !== false
	|| strpos($_SERVER['HTTP_USER_AGENT'], 'Silk/') !== false
	|| strpos($_SERVER['HTTP_USER_AGENT'], 'Kindle') !== false
	|| strpos($_SERVER['HTTP_USER_AGENT'], 'BlackBerry') !== false
	|| strpos($_SERVER['HTTP_USER_AGENT'], 'Opera Mini') !== false ) {
		$status = true;
	} else {
		$status = false;
	}
	return $status;
}

/**
 *  生成上传图片js,list参数存在时为编辑;
 * $arr = array('del_confirm'=>'false','process_url'=>'','list'=>array('0'=>array('filepath'=>'xx0.jpg','id'=>'1'),'1'=>array('filepath'=>'xx1.jpg','id'=>'2'))) ; 编辑必须有 list 参数,del_confirl 跟process_url 为可选
 * @author lee
 */ 
function getUploadImgCode($containerid='imgup',$channel='defautl',$arms=array()){
	$arrConfig = Config::get('file');
	$config = $arrConfig['CHANNEL_UPLOADIMG_CONFIG'];
	$params = is_array($config[$channel]) ? $config[$channel] : $config['default'];
	if(!empty($arms) && is_array($arms)){  //新的参数覆盖配置参数;
		$params = array_merge($params,$arms);
	}
	if($params['list']){  //编辑
		$arr = json_encode($params['list']);
		if((!$params['del_confirm'])){
			$params['del_confirm']='false';
		}
		if((!$params['process_url'])){
			$params['process_url']='';
		}
		$imgJsCode = <<<leeedit
    $.imgUploader({
        containerid:'$containerid',           
        dir:'$params[alias]',     
        img_cnt_limit:$params[img_cnt_limit],              
        max_file_size:$params[max_file_size],               
        prevent_duplicates:$params[prevent_duplicates],      
        extensions:'$params[extensions]', 
        multi_selection:$params[multi_selection], 
        min_img_width:$params[min_img_width], 
        min_img_height:$params[min_img_height],
        single_file:$params[single_file],
        del_confirm: $params[del_confirm],
		olds : {
			process_url: '$params[process_url]',
			list: $arr
		}
    });
leeedit;
}else{
	$imgJsCode =  <<<lee
    $.imgUploader({
        containerid:'$containerid',           
        dir:'$params[alias]',     
        img_cnt_limit:$params[img_cnt_limit],              
        max_file_size:$params[max_file_size],               
        prevent_duplicates:$params[prevent_duplicates],      
        extensions:'$params[extensions]', 
        multi_selection:$params[multi_selection], 
        min_img_width:$params[min_img_width], 
        min_img_height:$params[min_img_height],
        single_file:$params[single_file]
    });
lee;
}
return $imgJsCode;
}


/**
 *  ajax分页
 *  $tt 总页数 $list 每页条数 $page 当前页 $ty 函数名 $args 参数
 * @author lee
 */ 

function ajax_page($tt=0,$list = 10,$page = 1,$ty = 'getPage',$args =array()){
	$tpn = ceil($tt/$list); //总页数
	if($tt<=0 || $tpn<=1 || $tt<$list){
		$res['tt'] = $tt;
		$res['lpage'] = $list;
		$res['showmes'] = '<a href="javascript:;">当前第'.$page.'/'.($tpn<1? $tpn+1 : $tpn).'页</a>';
		$res['first']='<a href="javascript:;">[首页]</a>';
		$res['prev']='<a href="javascript:;">[上一页]</a>';
		$res['next']= '<a href="javascript:;">[下一页]</a>';
		$res['last']= '<a href="javascript:;">[尾页]</a>';
        $res['output'] = $res['showmes'];
		return $res;
	}
	if(!empty($args)){
		$st =",'".implode("','",$args)."'";
	}else{
		$st ="";
	}
	$fpage = ($page-5>0)?$page-5:1;
	if($page+5<$tpn){
		$lpage = $page+5;
	}else{
		$lpage = $tpn;
		$fpage = $tpn - 9;
	}
	$lpage = ($fpage ==1)?10:$lpage;
	$res['tt'] = $tt;
	$res['lpage'] = $list;
	$res['showmes'] =  '<a href="javascript:;">当前第'.$page.'/'.$tpn.'页</a>';
	$res['first']= ($page==1) ? '<a href="javascript:;">[首页]</a>' : '<a href="javascript:;" onclick="'.$ty.'(\'1\''.$st.')">[首页]</a>';
	$res['prev']=($page>=2) ? '<a href="javascript:;" onclick="'.$ty.'(\''.($page-1).'\''.$st.')">[上一页]</a>' : '<a href="javascript:;">[上一页]</a>';
	for($i=(($fpage > 0)?$fpage : 1);$i<=$lpage;$i++){
        if($i==1){
            $res['list'][$i]= '<a style="color:red;" href="javascript:void(0);" onclick="'.$ty.'(\''.$i.'\''.$st.')">'.$i.'</a>';
        }else{
            $res['list'][$i]= '<a href="javascript:void(0);" onclick="'.$ty.'(\''.$i.'\''.$st.')">'.$i.'</a>';
        }
        
    }
	$res['next']= ($page != $tpn) ? '<a href="javascript:;" onclick="'.$ty.'(\''.($page+1).'\''.$st.')">[下一页]</a>' : '<a href="javascript:;">[下一页]</a>';
	$res['last']= ($page==$tpn) ? '<a href="javascript:;">[尾页]</a>' : '<a href="javascript:;" onclick="'.$ty.'(\''.$tpn.'\''.$st.')">[尾页]</a>';
	//$res['output']  = $res['showmes'].$res['first'].$res['prev'];
	$res['output']  = $res['prev'];
	if(!empty($res['list'])){
		foreach($res['list'] as $v){
			$str .= $v;
		}
		$res['output'] .=$str;
	}
	//$res['output'] .= $res['next'].$res['last'];
	$res['output'] .= $res['next'];

	return $res;
}




/**
 * 时间转化函数
 *
 * @param $now
 * @param $datetemp
 * @param $dstr
 * @return string
 */
function smartDate($datetemp, $dstr = 'Y-m-d H:i') {
	$op = '';
	$sec = time() - $datetemp;
	$hover = floor($sec / 3600);
	if ($hover == 0) {
		$min = floor($sec / 60);
		if ($min == 0) {
			$op = $sec . ' 秒前';
		} else {
			$op = "$min 分钟前";
		}
	} elseif ($hover < 24) {
		$op = "约 {$hover} 小时前";
	} else {
		$op = date($dstr, $datetemp);
	}
	return $op;
}

function mbStringToArray($string, $encoding = 'UTF-8')
{
	$arrayResult = array();
	while ($iLen = mb_strlen($string, $encoding))
	{
		array_push($arrayResult, mb_substr($string, 0, 1, $encoding));
		$string = mb_substr($string, 1, $iLen, $encoding);
	}
	return $arrayResult;
}

function levenshtein_distance($str1, $str2, $costReplace = 1, $encoding = 'UTF-8') {
	$count_same_letter = 0;
	$d = array();
	$mb_len1 = mb_strlen($str1, $encoding);
	$mb_len2 = mb_strlen($str2, $encoding);

	$mb_str1 = mbStringToArray($str1, $encoding);
	$mb_str2 = mbStringToArray($str2, $encoding);

	for ($i1 = 0; $i1 <= $mb_len1; $i1++) {
		$d[$i1] = array();
		$d[$i1][0] = $i1;
	}

	for ($i2 = 0; $i2 <= $mb_len2; $i2++) {
		$d[0][$i2] = $i2;
	}

	for ($i1 = 1; $i1 <= $mb_len1; $i1++) 
	{
		for ($i2 = 1; $i2 <= $mb_len2; $i2++) 
		{
			// $cost = ($str1[$i1 - 1] == $str2[$i2 - 1]) ? 0 : 1;
			if ($mb_str1[$i1 - 1] === $mb_str2[$i2 - 1]) 
			{
				$cost = 0;
				$count_same_letter++;
			}
			else 
			{
				$cost = $costReplace; //替换
			}
			$d[$i1][$i2] = min($d[$i1 - 1][$i2] + 1, //插入
			$d[$i1][$i2 - 1] + 1, //删除
			$d[$i1 - 1][$i2 - 1] + $cost);
		}
	}
	return $d[$mb_len1][$mb_len2];
	//return array('distance' => $d[$mb_len1][$mb_len2], 'count_same_letter' => $count_same_letter);
}


?>